package com.lgcns.weather;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.lgcns.weather.db.QueryHelper;

/**
 * 날씨 정보를 보여주기 위한 메인 Activity
 */
public class FavoriteLocationActivity extends Activity implements OnClickListener, OnItemClickListener {
    private static final String TAG = "FavoriteLocationActivity";

    private ViewFlipper flipper;
    private Button cancel;
    private Button goUp;
    private TextView selectedLocation;
    private ListView loc1ListView;
    private ListView loc2ListView;
    private ListView loc3ListView;

    private int selectedLocId;
    private String selectedLoc1;
    private String selectedLoc2;
    private String selectedLoc3;

    private ArrayList<String> loc1List;
    private ArrayList<String> loc2List;
    private ArrayList<Integer> loc3IdList;
    private ArrayList<String> loc3List;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.favorite_location);

        flipper = (ViewFlipper) findViewById(R.id.favorite_flipper);
        cancel = (Button) findViewById(R.id.cancel_loc_btn);
        goUp = (Button) findViewById(R.id.go_up_btn);
        selectedLocation = (TextView) findViewById(R.id.favorite_location_selection);
        loc1ListView = (ListView) findViewById(R.id.loc1ListView);
        loc2ListView = (ListView) findViewById(R.id.loc2ListView);
        loc3ListView = (ListView) findViewById(R.id.loc3ListView);

        cancel.setOnClickListener(this);
        goUp.setOnClickListener(this);
        loc1ListView.setOnItemClickListener(this);
        loc2ListView.setOnItemClickListener(this);
        loc3ListView.setOnItemClickListener(this);

        setLoc1ListAdapter();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            // 취소 버튼
            case R.id.cancel_loc_btn:
                finish();
                break;
            // 상위 버튼
            case R.id.go_up_btn:
                int currentViewId = flipper.getCurrentView().getId();
                switch (currentViewId) {
                    case R.id.loc1ListView:
                        // 경우 없음
                        break;
                    case R.id.loc2ListView:
                        selectedLocation.setText(null);
                        goUp.setEnabled(false);
                        showPreviousFlipper();
                        break;
                    case R.id.loc3ListView:
                        selectedLocation.setText(selectedLoc1);
                        showPreviousFlipper();
                        break;
                }
                break;
        }
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // Back 키가 눌려졌을 때의 처리(1단계:종료, 2,3단계:이전으로 이동)
        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() && !event.isCanceled()) {
            int currentViewId = flipper.getCurrentView().getId();
            switch (currentViewId) {
                case R.id.loc1ListView:
                    finish();
                    return true;
                case R.id.loc2ListView:
                    selectedLocation.setText(null);
                    goUp.setEnabled(false);
                    showPreviousFlipper();
                    return true;
                case R.id.loc3ListView:
                    selectedLocation.setText(selectedLoc1);
                    showPreviousFlipper();
                    return true;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long resId) {
        switch (parent.getId()) {
            case R.id.loc1ListView:
                // 선택 지역 표시 및 하위 단계 지역 조회
                selectedLoc1 = loc1List.get(position);
                selectedLocation.setText(selectedLoc1);
                setLoc2ListAdapter();
                goUp.setEnabled(true);
                showNextFlipper();
                break;
            case R.id.loc2ListView:
                // 선택 지역 표시 및 하위 단계 지역 조회
                selectedLoc2 = loc2List.get(position);
                selectedLocation.setText(selectedLoc1 + " " + selectedLoc2);
                setLoc3ListAdapter();
                showNextFlipper();
                break;
            case R.id.loc3ListView:
                // 선택 지역 표시
                selectedLoc3 = loc3List.get(position);
                selectedLocId = loc3IdList.get(position);
                String selectedLocationText = selectedLoc1 + " " + selectedLoc2 + " " + selectedLoc3;
                selectedLocation.setText(selectedLocationText);

                // 확인 Dialog
                String message = String.format(getResources().getString(R.string.confirm_favorite_dialog_message), selectedLocationText);
                
                new AlertDialog.Builder(this).setTitle(R.string.confirm_favorite_dialog_title)
                        .setMessage(message)
                        .setPositiveButton(R.string.yes_button_text, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // 호출한 Activity에 데이터를 전달하고 종료
                                Intent intent = getIntent();
                                intent.putExtra(HurryWeatherActivity.PREF_FAVORITE_LOCATION_ID, selectedLocId);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        }).setNegativeButton(R.string.no_button_text, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
                break;
        }
    }

    /**
     * 상위 지역 목록으로 이동
     */
    private void showPreviousFlipper() {
        flipper.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.push_right_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.push_right_out));
        flipper.showPrevious();
    }

    /**
     * 하위 지역 목록으로 이동
     */
    private void showNextFlipper() {
        flipper.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.push_left_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.push_left_out));
        flipper.showNext();
    }

    /**
     * Loc1(시/도) 선택 ListView 데이터 생성
     */
    private void setLoc1ListAdapter() {
        loc1List = QueryHelper.getLoc1List(this);
        ArrayAdapter<String> loc1ListAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, loc1List);
        loc1ListView.setAdapter(loc1ListAdapter);
    }

    /**
     * Loc2(구/군) 선택 ListView 데이터 생성
     */
    private void setLoc2ListAdapter() {
        loc2List = QueryHelper.getLoc2List(this, selectedLoc1);
        ArrayAdapter<String> loc2ListAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, loc2List);
        loc2ListView.setAdapter(loc2ListAdapter);
    }

    /**
     * Loc3(동/면) 선택 ListView 데이터 생성
     */
    private void setLoc3ListAdapter() {
        HashMap<String, ArrayList> map = QueryHelper.getLoc3List(this, selectedLoc1, selectedLoc2);
        loc3IdList = (ArrayList<Integer>) map.get("id");
        loc3List = (ArrayList<String>) map.get("loc3");
        ArrayAdapter<String> loc3ListAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, loc3List);
        loc3ListView.setAdapter(loc3ListAdapter);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 화면 회전시 호출되는 메소드. 아무것도 수행하지 않는다.
        // 아무것도 수행하지 않으면, 현재의 layout이 회전된 화면에 맞게 줄거나 늘어나서 보여진다.
    }

}